package com.gzsxy.esjy.service.netty.service;


import com.gzsxy.esjy.common.Assert;
import com.gzsxy.esjy.request.impl.FileHttpServletRequest;
import com.gzsxy.esjy.service.netty.decoder.FilePathParser;
import com.gzsxy.esjy.service.netty.fileServer.configure.ServerStaticProperties;
import com.gzsxy.esjy.thread.FileOperateRunnable;
import com.gzsxy.esjy.thread.NettyServicePool;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

/**
 * 文件处理service
 * @author zhangxiaolong
 * @date 2022/7/11 9:36
 */
@Service
public class FileDownLoadService {

	@Autowired
	private NettyServicePool pool ;
	@Autowired
	private FileUploadService fileUploadService ;

	/**
	 * 获取额外线程池
	 * @return
	 */
	public NettyServicePool getServicePool() {
		return pool;
	}


	/**
	 * 文件下载
	 * @param filePath
	 * @param ctx
	 * @param resourcesRoot
	 * @return
	 * @throws IOException 
	 */
	public void downloadFile(FilePathParser filePath, ChannelHandlerContext ctx, String resourcesRoot, FileHttpServletRequest request) throws IOException {
		String directIndex = filePath.getDirectIndex();
		String oriDirectIndex = filePath.getOriDirectIndex();
		String  path = null ;
		//判断是否改变图片
		if(filePath.change()) {
			path = fileUploadService.createnewPhoto(filePath, resourcesRoot, directIndex, oriDirectIndex) ;
		}else {
			path = resourcesRoot + directIndex;
			File file = new File(path) ;
			Assert.notTrue(file.exists() && !file.isHidden() && !file.isDirectory() && file.isFile(),String.format("file[%s] not found", directIndex), HttpResponseStatus.NOT_FOUND.code());
		}

		File aim = new File(path) ;
		Runnable run = null ;
		String range = request.getHeader("Range");
		if(range != null && !"".equals(range)){
			//采用多线程处理（断点续传）
			run = new PlayRunnable(aim,ctx,request.isKeepAlive(),range) ;
		}else{
			//默认
			run = new FileOperateRunnable(aim, ctx, request.isKeepAlive()) ;
		}

		if(ServerStaticProperties.THREAD_ENABLED) {
			pool.start(run);
		}else {
			run.run();
		}
	}


	
	
}
